<template>
  <van-nav-bar title="注册"></van-nav-bar>
  <van-form @submit="onSubmit">
    <van-cell-group inset>
      <van-field v-model="UserForm.username" name="username" label="用户名" placeholder="用户名" :rules="[{ required: true, message: '请填写用户名' },
      {
        pattern: /^\w{6,16}$/, message: '用户名只能为6到16位的字母数字或者下划线'
      }]" />
      <van-field v-model="UserForm.password" name="password" type="password" label="密码" placeholder="密码" :rules="[{ required: true, message: '请填写密码' },
      {
        pattern: /^\w{6,16}$/, message: '密码的长度为6-16位'
      }]" />
      <van-field v-model="UserForm.confirmpassword" name="confirmpassword" type="password" label="重复密码"
        placeholder="再次输入密码" :rules="[{ required: true, message: '请再次输入密码' }, {
               validator(value: string){
              if(value!== UserForm.password) return false
              return true // 成功校验
            },
            message: '两次输入密码必须一致'
        }]" />
    </van-cell-group>
    <div style="margin: 16px;">
      <van-button round block type="primary" native-type="submit">
        注册
      </van-button>
    </div>
    <van-row justify="end">
      <router-link class="link" to="/login">已有账号去登录</router-link>
    </van-row>

  </van-form>

</template>
<script lang="ts" setup>
import type { RegisterUser } from '@/types/data'
import { reactive } from 'vue'
import { register } from '@/api/user'
import { Notify } from 'vant'
import 'vant/es/notify/style';

import { useRouter } from 'vue-router'
import type { AxiosError } from 'axios'

const router = useRouter()
// 用户表单
const UserForm = reactive<RegisterUser>({
  username: '',
  password: '',
  confirmpassword: ''
})
const onSubmit = async (values: RegisterUser) => {
  try {
    delete values.confirmpassword // 删除确认密码
    await register(values)
    Notify({ type: 'success', message: '注册成功' })
    router.push("/login")
  } catch (error) {
    const e = error as AxiosError
    Notify({ type: "danger", message: e.message })
  }

}
</script>
<style scoped>
.link {
  color: #069;
  font-size: 12px;
  padding-right: 20px;
}
</style>